package com.cqu.lpss.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

public class AliOSSProjectUtils {
    public String upload(MultipartFile uploadfile,String bucketName)throws IOException {
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
//        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        //不从环境变量中获取,直接写入
        String accessKeyId = "LTAI5tJM6vS2ruTa7A5tJ7u7";
        String accessKeySecret = "OH4wVDFLjroBQkqZWR1PJ5iDb0Ov6E";
        // 需要修改bucketName
//        String bucketName = "cqudemo1";



        //获取上传文件的输入流
        InputStream inputStream = uploadfile.getInputStream();
        String originalFilename = uploadfile.getOriginalFilename();
        String fileName = UUID.randomUUID().toString()+originalFilename.substring(originalFilename.lastIndexOf("."));
        //上传文件到OSS
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId,accessKeySecret);
        // 创建PutObjectRequest对象。
        ossClient.putObject(bucketName,fileName,inputStream);
//        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, inputStream);
//        // 创建PutObject请求。
//        PutObjectResult result = ossClient.putObject(putObjectRequest);
        String url = endpoint.split("//")[0]+"//"+bucketName+"."+endpoint.split("//")[1]+"/"+fileName;
        ossClient.shutdown();
        return url;
    }
}
